<template>
    <view>
        <view style="padding-bottom: 140rpx" v-if="sceneList.length > 0">
            <view class="card-list">
                <checkbox-group @change="checkboxChange">
                    <label class="card-list-item" v-for="(item, index) in sceneList" :key="item.sceneId">
                        <j-cell-card class='modeList' :title="item.sceneName" style="height: 160rpx" :more="false" :is-touch="false" :stop-propagation="false">
                            <view slot="tips">
                                <checkbox :value="item.sceneId" :checked="item.checked" />
                            </view>
                            <view style="padding:0 20rpx;">
                                <image :src="item.iconValueEncode" lazy-load :style="'width:64rpx;height:64rpx;border-radius:100%; background:'+item.colorValue"></image>
								<text v-if="item.description" style="font-size: 24rpx; color: #999999">{{ item.description }}</text>
                            </view>
                        </j-cell-card>
                    </label>
                </checkbox-group>
            </view>

            <view class="bottom-fixed">
                <button type="primary" class="block radius-btn" @tap="onBindtap">确认</button>
            </view>
        </view>

        <view v-else>
            <view class="empty">
                <view>
					<uni-icons custom-prefix="iconfont" type="icon-kong" size="64"></uni-icons>
                    <view>暂无场景数据</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// pages/scene/action-copy/action-copy.js
export default {
    data() {
        return {
            sceneId: '',
            // 当前场景ID
            sceneList: [],
            // 场景列表
            selectSceneIdList: [],
            // 选中的场景ID数组集合
            enter: false
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        console.log('=== scene:action-copy:onLoad:');
        
        if (options.enter === 'true') {
            this.enter = true
        } else {
			this.enter = false
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('=== scene:action-copy:onReady:');
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('=== scene:action-copy:onShow:');
        this.getSceneList();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('--- scene:action-copy:onHide:');
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        console.log('--- scene:action-copy:onUnload:');
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 查询场景列表
        getSceneList() {
            let isEditScene = uni.getStorageSync('isEditScene');
            let sceneId = uni.getStorageSync('scene').sceneId;
            const data = {
                groupId: uni.getStorageSync('currentGroupId'),
                // getApp().globalData.currentGroupId,
                isDefault: 0
            };
            getApp().globalData.api.getSceneList(data, (result) => {
                console.log('非默认场景列表：', result);
				result.forEach((item) => {
				    item.iconValueEncode = `${getApp().globalData.iconUrl}?rgb=${encodeURIComponent('#FFFFFF')}&url=${item.iconValue}`;
				});
                // 编辑已有场景
                if(isEditScene){
                    result = result.filter((o) => {
	                    return o.sceneId !== sceneId && o.invalid == 0
	                })
                }
				this.sceneList = result
                this.defaultSelected();
            });
        },

        // // 使用此场景
        // onBindtapScene(ev) {
        //     let scene = ev.currentTarget.dataset.scene
        //     let actionList = wx.getStorageSync('scene').actionList // getApp().globalData.scene.actionList
        //     let bool = false // 判断是否有缓存
        //     // 更新
        //     for (let i = 0; i < actionList.length; i++) {
        //         const item = actionList[i];
        //         if (item.actionRefId === scene.sceneId) {
        //             bool = true
        //             wx.showToast({
        //                 title: '该场景已存在'
        //             })
        //             break
        //         }
        //     }
        //     // 创建
        //     if (!bool) {
        //         actionList.push({
        //             actionType: 2,
        //             actionRefId: scene.sceneId,
        //             actionName: scene.sceneName,
        //             refScene: scene,
        //             actionValue: {
        //                 isEnable: scene.isEnable
        //             }
        //         })
        //         wx.setStorageSync('actionList', actionList)
        //         wx.navigateBack({
        //             delta: 1,
        //         })
        //     }
        // },
        // 比较定位原有选中的项
        defaultSelected() {
            let actionList = uni.getStorageSync('scene').actionList; // getApp().globalData.scene.actionList

            let selectSceneIdList = [];

            for (let i = 0; i < this.sceneList.length; i++) {
                const item = this.sceneList[i];
                item.checked = false;

                for (let j = 0; j < actionList.length; j++) {
                    const pro = actionList[j];

                    if (item.sceneId === pro.actionRefId) {
                        item.checked = true;
                        selectSceneIdList.push(item.sceneId);
                        break;
                    }
                }
            }

            this.selectSceneIdList = selectSceneIdList
        },

        // 选择场景，会生成一个由场景ID组成的数组
        checkboxChange(ev) {
            this.selectSceneIdList = ev.detail.value
        },

        // 生成ActionList
        setActionList() {
            let actionList = [];
            for (let i = 0; i < this.sceneList.length; i++) {
                const item = this.sceneList[i];

                for (let j = 0; j < this.selectSceneIdList.length; j++) {
                    const id = this.selectSceneIdList[j];
                    if (item.sceneId === id) {
                        let action = {
                            actionType: 2,
                            actionRefId: item.sceneId,
                            actionName: item.sceneName,
                            actionValue: {
                                isEnable: item.isEnable
                            },
							invalid:item.invalid,
							// sceneId:item.sceneId
                        };
                        actionList.push(action);
                        break;
                    }
                }
            }

            return actionList;
        },

        // 确认按钮
        onBindtap() {
            let actionList = uni.getStorageSync('scene').actionList; // getApp().globalData.scene.actionList

            let newActionList = this.setActionList();

            for (let i = 0; i < actionList.length; i++) {
                const item = actionList[i];

                if (item.actionType === 0) {
                    newActionList.unshift(item);
                }
            } // getApp().globalData.scene.actionList = newActionList
            // scene.actionList = newActionList
            // wx.setStorageSync('scene', scene)

            getApp().syncScene(this, {
                actionList: newActionList
            });
            uni.navigateBack({
                delta: this.enter ? 1 : 2
            });
        }
    }
};
</script>
<style lang="scss">
.card-list {
    width: auto;
    position: relative;
    overflow: hidden;
}
.card-list-item {
    float: left;
    display: inline;
    width: calc(50vw - 30rpx);
    margin: 20rpx 0 0 20rpx;
    position: relative;
}
/deep/.modeList {

		.cell-left {
			width: 70%;
		}

		.cell-headline {
			width: 100%;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
	}
</style>
